import Taro from "@tarojs/taro";
import getBaseUrl from "./baseUrl";
import { HTTP_STATUS } from "./config";
import { STORAGE_DATA } from "./constant";
import interceptors from "./interceptors";
import { createNonceSt, MD5withRSA, pageToLogin, signjs } from "./utils";

interceptors.forEach(interceptorItem => Taro.addInterceptor(interceptorItem));

class httpRequest {
  baseOptions(params, method = "GET") {
    let { url, data } = params;
    //添加token 随机数 sign
    if (Taro.getStorageSync(STORAGE_DATA.TOKEN))
      data.token = Taro.getStorageSync(STORAGE_DATA.TOKEN);
    if (!data.retrieveIntervalTime) data.retrieveIntervalTime = 60000;
    if (!data.retrieveTime) data.retrieveTime = new Date().getTime();

    data.nonce = createNonceSt();
    data.sign = MD5withRSA(signjs(data));
    const BASE_URL = getBaseUrl(url);
    let contentType = "application/json";
    contentType = params.contentType || contentType;
    const option = {
      url: BASE_URL + url, //地址
      data: data, //传参
      method: method, //请求方式
      timeout: 50000, // 超时时间
      header: {
        "content-type": contentType,
        Authorization: `Bearer ${Taro.getStorageSync(STORAGE_DATA.TOKEN)}`
      }
    };
    // return Taro.request(option);
    if (process.env.NODE_ENV === "development") {
      console.log(
        `${new Date().toLocaleString()}【 M=${option.url} 】P=${JSON.stringify(
          option.data
        )}`
      );
    }
    return Taro.request(option)
      .then(res => {
        console.log("resres", res);
        if (res) {
          if (
            res.code >= HTTP_STATUS.SUCCESS &&
            res.code < HTTP_STATUS.MULTI_SELECT
          ) {
            if (process.env.NODE_ENV === "development") {
              console.log(
                `${new Date().toLocaleString()}【 M=${
                  option.url
                } 】【接口响应：】`,
                res
              );
            }
            return res;
          } else {
            throw new Error(
              `${res.desc || "网络请求错误，状态码"}(${res.code})`
            );
          }
        } else {
          throw new Error(`数据返回异常，请重试`);
        }
      })
      .catch(error => {
        console.log("http error", error);
        Taro.showToast({ title: error.message || "服务异常", icon: "none" });
        // pageToLogin()
        // return null;
      });
  }

  get(url, data = "") {
    let option = { url, data };
    return this.baseOptions(option);
  }

  post(url, data, contentType) {
    let params = { url, data, contentType };
    return this.baseOptions(params, "POST");
  }

  put(url, data = "") {
    let option = { url, data };
    return this.baseOptions(option, "PUT");
  }

  delete(url, data = "") {
    let option = { url, data };
    return this.baseOptions(option, "DELETE");
  }
}

export default new httpRequest();
